package cn.sofwin.boot.config;

import cn.sofwin.core.support.utils.JsonUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.HashMap;
import java.util.Map;

@Component
public class LoginInterceptor implements HandlerInterceptor {
    @Autowired
    RedisTemplate<String ,Object> redisTemplate;

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        System.out.println("拦截器开始工作");
        String method = request.getMethod();
        if("OPTIONS".equals(method)){
            return true;
        }
        String token = request.getHeader("Authorization");
        if(StringUtils.isBlank(token)){
            //返回没有权限的信息
            setErrorMsg(response);
        }else {
            if (redisTemplate.hasKey("LOGIN_TOKEN_"+token)){
                return true;
            }else {
                setErrorMsg(response);
            }
        }
        System.out.println("token:"+token);
        return false;
    }
    /**
     * 返回401告知未登录
     * @param response
     */
    private void setErrorMsg(HttpServletResponse response) {
        response.setStatus(HttpServletResponse.SC_UNAUTHORIZED);
        response.setContentType("application/json;charset=UTF-8");


        Map<String, Object> info = new HashMap<String, Object>();
        info.put("msg", "用户未登录");
        try {
            response.getWriter().write(JsonUtils.toJSON(info));
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}
